/*
 * Copyright 2015 Eduard Ereza Martínez
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.administrator.dagger2demo.execption.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;


import com.example.administrator.dagger2demo.R;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;

/**
 * 异常显示类
 */
public final class DefaultErrorActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.customactivityoncrash_default_error_activity);

        //Close/restart button logic:
        //If a class if set, use restart.
        //Else, use close and just finish the app.
        //It is recommended that you follow this logic if implementing a custom error activity.
        Button restartButton = (Button) findViewById(R.id.customactivityoncrash_error_activity_restart_button);

        final Class<? extends Activity> restartActivityClass = CustomActivityOnCrash.getRestartActivityClassFromIntent(getIntent());

        if (restartActivityClass != null) {
            restartButton.setText("重新启动APP");
            restartButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(DefaultErrorActivity.this, restartActivityClass);
                    CustomActivityOnCrash.restartApplicationWithIntent(DefaultErrorActivity.this, intent);
                }
            });
        } else {
            restartButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CustomActivityOnCrash.closeApplication(DefaultErrorActivity.this);
                }
            });
        }

        Button moreInfoButton = (Button) findViewById(R.id.customactivityoncrash_error_activity_more_info_button);

        if (CustomActivityOnCrash.isShowErrorDetailsFromIntent(getIntent())) {

            moreInfoButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //We retrieve all the error data and show it
                    Toast.makeText(DefaultErrorActivity.this, "非常感谢您的反馈，我们会尽快处理！", Toast.LENGTH_SHORT).show();

                    //                    AlertDialog dialog = new AlertDialog.Builder(DefaultErrorActivity.this)
                    //                            .setTitle(R.string.customactivityoncrash_error_activity_error_details_title)
                    //                            .setMessage(CustomActivityOnCrash.getAllErrorDetailsFromIntent(DefaultErrorActivity.this, getIntent()))
                    //                            .setPositiveButton(R.string.customactivityoncrash_error_activity_error_details_close, null)
                    //                            .setNeutralButton(R.string.customactivityoncrash_error_activity_error_details_copy,
                    //                                    new DialogInterface.OnClickListener() {
                    //                                        @Override
                    //                                        public void onClick(DialogInterface dialog, int which) {
                    //                                            copyErrorToClipboard();
                    //                                            Toast.makeText(DefaultErrorActivity.this, R.string.customactivityoncrash_error_activity_error_details_copied, Toast.LENGTH_SHORT).show();
                    //                                        }
                    //                                    })
                    //                            .show();
                    //                    TextView textView = (TextView) dialog.findViewById(android.R.id.message);
                    //                    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.customactivityoncrash_error_activity_error_details_text_size));
                }
            });
        } else {
            moreInfoButton.setVisibility(View.GONE);
        }
        postException();
    }

    /**
     * 提交异常到服务器器
     */
    public void postException() {

        String errorDetail = CustomActivityOnCrash.getAllErrorDetailsFromIntent(DefaultErrorActivity.this, getIntent());
        sdcard(errorDetail);//本地文件
        final String[] errors = errorDetail.split(" \n");
        //        Log.i("errors", errors[0]);
        //        Log.i("errors", errors[1]);
        //        Log.i("errors", errors[2]);
        //        Log.i("errors", errors[3]);
        //        Log.i("errors", errors[4]);
        //        Log.i("errors", errors[5]);
        final HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("version", errors[0].toString());
//        map.put("builddate", errors[1].toString());
//        map.put("creatdate", errors[2].toString());
        map.put("device", errors[3].toString());
        map.put("trace", errors[5].toString());

        //网络请求存储异常信息...
    }

    public void sdcard(String error) {
        String fileName = "exception.log";
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String path = "/sdcard/crash/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName, true);
                fos.write(error.getBytes());
                fos.close();
            }
        } catch (Exception e) {
            //            Log.e(TAG, "an error occured while writing file...", e);
        }
    }


    @SuppressLint("NewApi")
    private void copyErrorToClipboard() {
        String errorInformation =
                CustomActivityOnCrash.getAllErrorDetailsFromIntent(DefaultErrorActivity.this, getIntent());

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            clipboard.setText(errorInformation);
        } else {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Error information", errorInformation);
            clipboard.setPrimaryClip(clip);
        }
    }
}
